// 角色管理页面
import React, { useState, useEffect } from 'react';
import {
  ReloadOutlined, FormOutlined,
  PlusSquareOutlined
} from '@ant-design/icons';
import { Row, Col, Button, Spin, Pagination, Popconfirm, notification, Alert } from 'antd';
import useStore from '../../components/useStore.js';
import { openNotification_util } from '../../components/ship/util/util.js';
import request from '../../untils/request.js';

const Role = () => {
  const [isloading, setisloading] = useState(false);
  const [ifshow, setifshow] = useState(true);
  const [listdata, setlistdata] = useState([]);
  const { setnowroute, collapsed } = useStore();
  const [currentPage, setcurrentPage] = useState(1); // 当前页
  const [total, settotal] = useState(10); // 总数

  useEffect(() => {
    querylist();
  }, []);

  useEffect(() => { ifshow ? "" : setifshow(true); }, [ifshow]);

  // 角色列表查询
  const querylist = async () => {
    setisloading(true);
    let rtdata = await request("/admin/role/getRoles", {
      method: "POST",
      body: {
        pageSize: 10,
        offset: (currentPage - 1) * 10
      }
    });
    setlistdata(rtdata.data);
    settotal(rtdata.total);
    setifshow(false);
    setisloading(false);
  };

  /**手动查询 */
  const handleQuery = async () => {
    querylist();
  };

  /**前往新增页面 */
  const handleadd = async () => {
    setnowroute({ ...{ route: "/ship/sys/addRoleForm", title: "新增角色" } });
  };

  const toEdit = (e) => { // 前往编辑页面
    if (e === 1 || e === 2) {
      notification.open({
        message: "超级管理员/默认用户不允许编辑"
      });
      return;
    }
    setnowroute({ ...{ route: `/ship/sys/editRoleForm?id=${e}`, title: "编辑角色" } });
  };

  const deleteRole = (e) => { // 删除角色
    request("/admin/role/delete", {
      method: 'POST',
      mode: 'cors',
      body:{
        role_id: e // 被删除的角色id
      }
    }).then(data => {
      if (data.code === 200) {
        notification.success({
          message: data.msg
        });
      } else {
        notification.error({
          message: data.msg
        });
        querylist();
      }
    });
  };

  const changePage = (e) => { // 改变当前页
    setcurrentPage(e);
  };

  useEffect(() => {
    querylist();
  }, [currentPage]);

  return (
    <div style={{
      height: "94%",
      right: "1%",
      top: "4vh",
      overflow: "hidden",
      backgroundSize: "100% 100%",
      width: collapsed ? "94%" : "84%",
      position: "absolute",
      color: "#1D2129", // 深色文字，提高可读性
      fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <div style={{
          width: "99vw",
          height: "",
          backgroundColor: "white",
          overflowX: "scroll",
          margin: "0.5vw",
          paddingLeft: "1vw"
        }}>
          <div style={styleobj.linestyleflex}>
            &nbsp;<Button
              style={{ backgroundColor: "white", color: "#165DFF", borderColor: "#165DFF", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery(); }}
            >
              <ReloadOutlined />刷新
            </Button>
            &nbsp;<Button
              style={{ backgroundColor: "#165DFF", color: "white", borderColor: "#165DFF", fontWeight: "800" }}
              onClick={handleadd}
            >
              <PlusSquareOutlined />新 增
            </Button>
          </div>
          <Alert
            style={{ width: collapsed ? "94%" : "84%" }}
            message="提示：删除角色后，所有归属于该角色的用户将被划分至“默认用户”角色。"
            type="warning"
            closable
          />
          {isloading ? (
            <div style={{
              width: "10%",
              height: "10%",
              position: "absolute",
              left: "50%",
              top: "49%",
              color: "#165DFF" // 蓝色加载图标
            }}>
              <Spin />
            </div>
          ) : (
            <div>
              <div>
                <Row
                  style={{
                    width: collapsed ? "94%" : "84%",
                    backgroundColor: "#1890ff", // 蓝色表头
                    color: "white",
                    marginTop: "1vh",
                    marginLeft: "0.25vw"
                  }}
                  gutter={24}
                >
                  <Col span={4}>序号</Col>
                  <Col span={12}>角色名称</Col>
                  <Col span={8}>操作</Col>
                </Row>
                <div style={{
                  height: "70vh",
                  overflowY: "auto",      // 纵向滚动（内容超出时显示）
                  overflowX: "hidden",    // 隐藏横向滚动条
                  paddingRight: "10px"    // 补偿滚动条宽度，防止内容被遮挡
                }}>
                  {listdata.map((item, index) => {
                    const isEvenRow = index % 2 === 0;
                    const rowBgColor = isEvenRow ? "#F9FAFB" : "#FFFFFF";
                    const hoverColor = "#E6F7FF"; // 蓝色系悬停色
                    return (
                      <Row
                        key={index}
                        style={{
                          width: collapsed ? "94%" : "84%",
                          marginTop: "0.5vh",
                          marginLeft: "0.25vw",
                          borderBottom: "1px solid #E8E8E8",
                          padding: "0.1rem",
                          backgroundColor: rowBgColor,
                          transition: "background-color 0.2s" // 平滑过渡效果
                        }}
                        onMouseEnter={(e) => e.currentTarget.style.backgroundColor = hoverColor}
                        onMouseLeave={(e) => e.currentTarget.style.backgroundColor = rowBgColor}
                        gutter={24}
                      >
                        <Col span={4}>{index + 1}</Col>
                        <Col span={12} style={{ whiteSpace: "normal", wordBreak: "break-all" }}>{item.role_name}</Col>
                        <Col span={8}>
                          <Button
                            onClick={() => toEdit(item.id)}
                            icon={<FormOutlined />}
                            disabled={item.id === 1 || item.id === 2} // 超级管理员与默认用户不允许编辑
                            style={{
                              marginRight: "8px",
                              color: (item.id === 1 || item.id === 2) ? "#C9C9C9" : "#165DFF",
                              borderColor: (item.id === 1 || item.id === 2) ? "#C9C9C9" : "#165DFF"
                            }}
                          >
                            编辑
                          </Button>
                          <Popconfirm
                            title="角色删除警告，如果您不是系统的开发/维护人员，请勿进行此操作！"
                            okText="确认删除"
                            cancelText="取消"
                            onConfirm={() => deleteRole(item.id)}
                          >
                            <Button danger disabled={item.is_sys === 1}>删除</Button>
                          </Popconfirm>
                        </Col>
                      </Row>
                    );
                  })}
                </div>
              </div>
              <Pagination
                current={currentPage}
                onChange={changePage}
                total={total}
                style={{ marginTop: "1vh" }}
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Role;

// 仅保留使用到的样式
const styles = {
  kshcontainer: {
    width: "100%",
    minHeight: "40vh",
    position: "absolute",
    top: "2vh",
    left: "0vw",
    color: "#1D2129" // 深色文字
  }
};

const styleobj = {
  linestyleflex: {
    height: "1.8rem",
    fontSize: "0.6rem",
    position: "relative",
    width: "96vw",
    marginLeft: "0.1%",
    display: "flex",
    justifyContent: "flex-start",
    alignItems: "center",
    marginBottom: "0.5rem",
    marginTop: "0.5rem"
  }
};
